import React, { useEffect } from "react";
import {
  TextField,
  Button,
  Typography,
  Container,
  Snackbar,
  Alert,
  InputAdornment,
} from "@mui/material";
import PublicIcon from "@mui/icons-material/Public";
import LinkIcon from "@mui/icons-material/Link";
import PersonIcon from "@mui/icons-material/Person";
import LockIcon from "@mui/icons-material/Lock";
import { FormattedMessage, useIntl } from "react-intl";
import PawIconWithText from "./PawIconWithText";

type EditionType = "cloud" | "community" | "enterprise";

interface Config {
  email: string;
  password: string;
  backendUrl: string;
  edition?: EditionType;
}

interface ConfigFormProps {
  vscode: {
    postMessage: (message: any) => void;
    getState: () => any;
  };
  initialConfig: Config;
  validateResult: boolean;
  onSubmit: (config: Config) => void;
  refresh: boolean;
}

const ConfigForm: React.FC<ConfigFormProps> = ({
  vscode,
  initialConfig,
  onSubmit,
  validateResult,
  refresh,
}) => {
  const defaultConfig = {
    ...initialConfig,
  };
  const [initFlag, setInitFlag] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  const [formState, setFormState] = React.useState<Config>(defaultConfig);
  const [snackbarOpen, setSnackbarOpen] = React.useState(false);
  const [snackbarMessage, setSnackbarMessage] = React.useState("");
  const [snackbarSeverity, setSnackbarSeverity] = React.useState<
    "success" | "error"
  >("success");
  const { formatMessage } = useIntl();

  React.useEffect(() => {
    setFormState(defaultConfig);
  }, [initialConfig]);

  const openExternalLink = (url: string) => {
    vscode.postMessage({ command: "openLink", url });
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    setLoading(true);
    setInitFlag(true);
    const submittingFormState = {
      ...formState,
      backendUrl: formState.backendUrl.replace(/\/+$/, ""),
    };

    await onSubmit(submittingFormState);
  };
  useEffect(() => {
    if (initFlag) {
      setSnackbarOpen(true);
      setLoading(false);
    }
  }, [refresh]);

  const handleInputChange = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = event.target;
    setFormState((prev) => {
      let newState = { ...prev, [name]: value };

      if (name === "edition") {
        switch (value as EditionType) {
          case "cloud":
            newState.backendUrl = "https://www.pawsql.com";
            newState.email = "";
            newState.password = "";
            break;
          case "community":
            newState.backendUrl = "";
            newState.email = "community@pawsql.com";
            newState.password = "community@pawsql.com";
            break;
          case "enterprise":
            newState.backendUrl = "";
            newState.email = "";
            newState.password = "";
            break;
        }
      }

      return newState;
    });
  };

  return (
    <Container
      maxWidth="sm"
      sx={{
        padding: "20px",
        "& .MuiTextField-root": {
          backgroundColor: "#ffffff",
          borderRadius: "4px",
          "& .MuiOutlinedInput-root": {
            "&:hover fieldset": {
              borderColor: "#007acc",
            },
          },
        },
      }}
    >
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          marginBottom: "24px",
          gap: "12px",
          textAlign: "center",
        }}
      >
        <PawIconWithText scale={0.5} />
        <Typography
          variant="body1"
          align="center"
          color="textSecondary"
          sx={{ maxWidth: "560px" }}
        >
          <FormattedMessage id="form.config.description" />{" "}
          <a
            href="#"
            onClick={() => openExternalLink("https://docs.pawsql.com")}
            style={{
              color: "#007acc",
              textDecoration: "underline",
            }}
          >
            <FormattedMessage id="form.config.documentation.link" />
          </a>
        </Typography>
      </div>
      <TextField
        select
        fullWidth
        name="edition"
        label={formatMessage({ id: "form.config.edition.label" })}
        variant="outlined"
        margin="normal"
        value={formState.edition}
        onChange={handleInputChange}
        SelectProps={{
          native: true,
        }}
        sx={{ mb: 2 }}
      >
        <option value="cloud">
          {formatMessage({ id: "form.config.edition.cloud" })}
        </option>
        <option value="community">
          {formatMessage({ id: "form.config.edition.community" })}
        </option>
        <option value="enterprise">
          {formatMessage({ id: "form.config.edition.enterprise" })}
        </option>
      </TextField>

      <TextField
        fullWidth
        name="backendUrl"
        label={formatMessage({ id: "form.config.backendUrl.label" })}
        variant="outlined"
        margin="normal"
        value={formState.backendUrl}
        onChange={handleInputChange}
        disabled={formState.edition === "cloud"}
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <PublicIcon sx={{ color: "#666" }} />
            </InputAdornment>
          ),
        }}
        sx={{ mb: 2 }}
      />
      <form onSubmit={handleSubmit}>
        <TextField
          fullWidth
          name="email"
          label={formatMessage({ id: "form.config.email.label" })}
          variant="outlined"
          margin="normal"
          value={formState.email}
          onChange={handleInputChange}
          disabled={formState.edition === "community"}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <PersonIcon sx={{ color: "#666" }} />
              </InputAdornment>
            ),
          }}
          sx={{ mb: 2 }}
        />
        <TextField
          fullWidth
          name="password"
          type="password"
          label={formatMessage({ id: "form.config.password.label" })}
          variant="outlined"
          margin="normal"
          value={formState.password}
          onChange={handleInputChange}
          disabled={formState.edition === "community"}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <LockIcon sx={{ color: "#666" }} />
              </InputAdornment>
            ),
          }}
          sx={{ mb: 2 }}
        />

        <Button
          type="submit"
          variant="contained"
          fullWidth
          disabled={loading}
          sx={{
            height: "48px",
            fontSize: "16px",
            backgroundColor: "#007acc",
            color: "#ffffff",
            textTransform: "none",
            boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",
            "&:hover": {
              backgroundColor: "#005999",
              boxShadow: "0 4px 8px rgba(0, 0, 0, 0.15)",
            },
            transition: "all 0.3s ease",
            mb: 2,
          }}
        >
          <FormattedMessage id="form.config.save" />
        </Button>

        <Button
          variant="outlined"
          fullWidth
          onClick={() =>
            openExternalLink(
              formState.edition === "community"
                ? "https://pawsql.com/community"
                : "https://www.pawsql.com"
            )
          }
          sx={{
            height: "48px",
            fontSize: "16px",
            color: "#007acc",
            borderColor: "#007acc",
            textTransform: "none",
            "&:hover": {
              backgroundColor: "#f0f8ff",
              borderColor: "#005999",
            },
            transition: "all 0.3s ease",
          }}
        >
          {formState.edition === "community" ? (
            <FormattedMessage id="form.config.joinPawSQL.community" />
          ) : (
            <FormattedMessage id="form.config.joinPawSQL" />
          )}
        </Button>
      </form>
      {snackbarOpen && (
        <Snackbar
          open={snackbarOpen}
          autoHideDuration={6000}
          onClose={() => setSnackbarOpen(false)}
          anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
        >
          <Alert
            onClose={() => setSnackbarOpen(false)}
            severity={validateResult ? "success" : "error"}
            sx={{
              width: "100%",
              boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
            }}
          >
            {validateResult
              ? formatMessage({ id: "webview.settings.save.config.success" })
              : formatMessage({ id: "webview.settings.save.config.failed" })}
          </Alert>
        </Snackbar>
      )}
    </Container>
  );
};

export default ConfigForm;
